#coding=utf-8
import requests
import base64
import hashlib
import time
import random
import os, string, glob
from PIL import Image
from io import BytesIO
from urllib.parse import urlencode
from urllib import parse
import json



AppID = '1106747980'
AppKey = 'tByJAXRof60vsLJ8'


def get_random_str():
    """
    :return: 随机生成16位字符串
    """
    # 随机生成16位字符串
    rule = string.ascii_lowercase + string.digits  # 小写字母+数字
    str = random.sample(rule, 16)  # 16位随机字符串
    #print("".join(str))
    return "".join(str)


def get_time_stamp():
    """
    :return: 秒级时间戳
    """
    #print(str(int(time.time())))
    return str(int(time.time()))


def get_imgfile_base64str(image):
    """
    :param image:
    :return:原始图片的base64编码数据（原图大小上限1MB，支持JPG、PNG、BMP格式）
    """
    with open(image, 'rb') as fp:
        imgbase64 = base64.b64encode(fp.read()).decode()
        #print(str(imgbase64))
    #print(str(imgbase64))
    #img_base64str = imgbase64(image)
    #print(img_base64str)
    return imgbase64


def gen_req_dict(req_dict,value,app_id,time_stamp,nonce_str,app_key):
    req_dict['image'] = value
    req_dict['app_id'] = app_id
    req_dict['time_stamp'] = time_stamp
    req_dict['nonce_str'] = nonce_str
    #print(req_dict)

    # 按key进行字典升序排序
    sort_dict = sorted(req_dict.items(), key=lambda item: item[0], reverse=False)
    #print(sort_dict)
    sort_dict.append(('app_key', app_key))  # app_key为键名，组成URL键值拼接到字符串T末尾
    #print(sort_dict)

    sha = hashlib.md5()
    rawtext = urlencode(sort_dict).encode()
    #print(rawtext)
    sha.update(rawtext)
    md5text = sha.hexdigest().upper()
    #print(md5text)
    req_dict['sign'] = md5text
    #print(req_dict)
    return req_dict

def ExecTecentAPI(url,Req_Dict):
    """
    构造网络请求，返回结果
    :param url:
    :param Req_Dict:
    :return:
    """
    resp = requests.post(url, data=Req_Dict)
    #sign = gen_req_dict(req_dict=Req_Dict)
    # print(resp.text,type(resp.text))
    return resp.text

def tencent_ocr(image):
    req_dict ={}
    # image = 'pic4.jpg'#r'1703qt00068_58_08500.jpg'
    # image = "shouju.jpg"
    value = get_imgfile_base64str(image)
    get_dict = gen_req_dict(req_dict=req_dict,value=value,app_id=AppID,time_stamp=get_time_stamp(),nonce_str=get_random_str(),app_key=AppKey)
    url = 'https://api.ai.qq.com/fcgi-bin/ocr/ocr_generalocr' #通用识别
    # url = "https://api.ai.qq.com/fcgi-bin/ocr/ocr_creditcardocr" #银行卡
    results = []
    to_dict = eval(ExecTecentAPI(url=url,Req_Dict=get_dict))
    #print(to_dict)
    #print(len(to_dict['data']['item_list']))
    #print(to_dict['data']['item_list'][0]['itemstring'])
    for i in range(0,len(to_dict['data']['item_list'])):
        # print(to_dict['data']['item_list'][i]['itemstring'])
        results.append(to_dict['data']['item_list'][i]['itemstring'])
    return results
if __name__ == '__main__':
    # req_dict ={}
    # # image = 'pic4.jpg'#r'1703qt00068_58_08500.jpg'
    # image = "shouju.jpg"
    # value = get_imgfile_base64str(image)
    # get_dict = gen_req_dict(req_dict=req_dict,value=value,app_id=AppID,time_stamp=get_time_stamp(),nonce_str=get_random_str(),app_key=AppKey)
    # url = 'https://api.ai.qq.com/fcgi-bin/ocr/ocr_generalocr' #通用识别
    # # url = "https://api.ai.qq.com/fcgi-bin/ocr/ocr_creditcardocr" #银行卡
    # result = []
    # to_dict = eval(ExecTecentAPI(url=url,Req_Dict=get_dict))
    # #print(to_dict)
    # #print(len(to_dict['data']['item_list']))
    # #print(to_dict['data']['item_list'][0]['itemstring'])
    # for i in range(0,len(to_dict['data']['item_list'])):
    #     # print(to_dict['data']['item_list'][i]['itemstring'])
    #     result.append(to_dict['data']['item_list'][i]['itemstring'])
    # print(result)
    image = "shouju.jpg"
    results = tencent_ocr(image)
    print(results)